﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;
using System.Text;

namespace SUNRPA.CONTROLS.IMPL.controls {
    public class ReadFileNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            ReadFileNParam? param = item.ControlParam as ReadFileNParam;
            string filePath = param.FilePath;
            this.GetStringVar(ref filePath, globleData);
            if(!File.Exists(filePath)) { 
                throw new RpaRuntimeException("文件不存在");
            }
            Encoding encode = param.EncodingType;
            int saveType = param.SaveType;
            string outVarName = param.OutVarName;
            switch(saveType) {
                case 0:
                    this.saveVar(globleData, outVarName, new StringModel(outVarName, File.ReadAllText(filePath, encode)), DefaultContents.RUNNING_PARAM);
                    break;
                case 1:
                    List<string> list = new List<string>();
                    foreach(string line in File.ReadAllLines(filePath, encode)) { 
                        list.Add(line);
                    }
                    this.saveVar(globleData, outVarName, new ListModel<string>(outVarName, list), DefaultContents.RUNNING_PARAM);
                    break;
                case 2:
                    this.saveVar(globleData, outVarName, new OtherModel(outVarName, File.ReadAllBytes(filePath)), DefaultContents.RUNNING_PARAM);
                    break;
            }
            return currentIndex;
        }
    }
}
